const timeToSeconds = function (timeString) {
    let seconds = new Date(timeString).getTime();
    if (isNaN(seconds)) {
        return new Date().getTime();
    }
    return seconds;
}
const getTwo = function (number) {
    if (number < 10) {
        return "0" + number;
    } else
        return number + "";
};
const transDateToTimestamp = function (orginDate) {
    
    let year = parseInt(orginDate.split("年")[0]);
    let newString = orginDate.split("年")[1]
    
    let month = parseInt(newString.split("月")[0])-1;
    newString = newString.split("月")[1]
    
    let day = parseInt(newString.split("日")[0]);
    newString = newString.split("日")[1]

    let newStrings = newString.replace(" ", "").split(":");
    let hour = parseInt(newStrings[0])
    let min = parseInt(newStrings[1])
    let sec = parseInt(newStrings[2])
    let targetDate = new Date(year, month, day, hour, min, sec);
    console.log(targetDate)
    return targetDate.getTime();
}
const getTimestamp = function (date) {
    if (!date) {
        return new Date().getTime()
    }
}
const formatTime = function (date, fmt) {
    if (!wx.sqtools.isDate(date)) {
        date = new Date(date)
    }
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    let cfmt = "yyyy年MM月dd日 HH:mm:ss";
    if (fmt) {
        cfmt = fmt;
    }
    //yyyy-MM-dd hh:mm:ss
    //Year
    if (cfmt.search("yyyy") != 1) {
        cfmt = cfmt.replace("yyyy", year + '');
    } else if (cfmt.search("yy") != 1) {
        cfmt = cfmt.replace("yy", getTwo(year % 100));
    }

    //Month
    if (cfmt.search("MM") != -1) {
        cfmt = cfmt.replace("MM", getTwo(month));
    } else if (cfmt.search("M") != -1) {
        cfmt = cfmt.replace("M", month + '');
    }

    //Day
    if (cfmt.search("dd") != -1) {
        cfmt = cfmt.replace("dd", getTwo(day));
    } else if (cfmt.search("d") != -1) {
        cfmt = cfmt.replace("d", day + '');
    }

    //Hour
    if (cfmt.search("hh") != -1) {
        cfmt = cfmt.replace("hh", getTwo(hour % 12));
    } else if (cfmt.search("h") != -1) {
        cfmt = cfmt.replace("h", hour % 12 + '');
    } else if (cfmt.search("HH") != -1) {
        cfmt = cfmt.replace("HH", getTwo(hour));
    } else if (cfmt.search("H") != -1) {
        cfmt = cfmt.replace("H", hour + '');
    }

    //Minute
    if (cfmt.search("mm") != -1) {
        cfmt = cfmt.replace("mm", getTwo(minute));
    } else if (cfmt.search("m") != -1) {
        cfmt = cfmt.replace("m", minute);
    }

    //Second
    if (cfmt.search("ss") != -1) {
        cfmt = cfmt.replace("ss", getTwo(second));
    } else if (cfmt.search("s") != -1) {
        cfmt = cfmt.replace("s", second);
    }
    return cfmt;
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}
const checkPhone = function (phone) {
    if (isNaN(parseInt(phone))) {
        return false;
    }
    if (!(/^1[3456789]\d{9}$/.test(phone))) {
        return false;
    }
    return true;
}
const requestBackground = function (param, loadingTitle) {
    request(param, true, loadingTitle);
}
let Request_Utils_LoadingCount = 0;
const request = function (param, notShowLoading, loadingTitle) {
    let url = null;
    if (wx.sqtools.getClassType(param.url) == 'Object') {
        url = param.url.url;
        if (param.url.security) {
            param.securityMode = 'yes';
        }
    } else {
        url = param.url
    }

    if (!url || url == '') {
        console.log("参数错误");
        // throw error();
        return false;
    }
    if (!notShowLoading) {
        wx.showLoading({
            title: param.loadingTitle ? param.loadingTitle : "加载中···",
            mask: true
        });
        Request_Utils_LoadingCount++;
    }
    const publicKeyForRequestSm2 = "0418bfdf2a1ab8439f186b9f8b1e510f161e7fd81903d15ce6e5eb2fee0729295dd320db9eff6e7a4d1628dfe0a4eb5a067558f21c133a09a240e0128d6302085c";
    const publicKeyForRequestRsa2 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCNS6SrOY8Zm8TNbwTJLZi7zAvrbrR7Fg2C4MRIscJMcivwH3FyITZplhruU4R/c4zBXFRCS30YQxAhY0JRCMb5sycWf00gWXon8CGhsuw0mi6h9OxXUu25Hh15+dWocCY5OMNMlJ0yyaSHTvaBMIqbN5klEjE0CI32wbqCqHuBqQIDAQAB"
    let that = this;
    let header = {}
    if (param.withoutOau) {
        header = {};
    } else {
        header.Authorization = getApp().getToken();
    }
    if (wx.surls.is_security && (param.securityMode && param.securityMode == 'yes')) {
        header['data-encrypted'] = 'yes';
    }
    if (wx.surls.is_security && (param.securityMode && param.securityMode == 'yes') && param.method && param.method.toLowerCase() == 'post') {

        if (param.data) {
            let data = param.data;
            let dataString = data;
            if (wx.sqtools.isObject(data) || wx.sqtools.isArray(data)) {
                dataString = JSON.stringify(data);
            }

            let encryptDataString = wx.sqtools.sm2.encrypt(dataString, publicKeyForRequestSm2);

            let firstDataContainer = {
                data: encryptDataString,
                timestamp: getTimestamp()
            }
            let firstDataContainerString = JSON.stringify(firstDataContainer);
            let dataSign = wx.sqtools.md5.hex_md5(firstDataContainerString);
            let secondDataContainer = {
                data: firstDataContainerString,
                sign: dataSign,
                timestamp: getTimestamp()
            }
            let rsa = wx.sqtools.createRasEncryptor(publicKeyForRequestRsa2);

            let finalDataString = rsa.encryptLong(JSON.stringify(secondDataContainer), publicKeyForRequestRsa2);
            param.data = finalDataString;
        }
    }

    wx.request({
        url: url,
        header: header,
        data: param.data ? param.data : "{}",
        dataType: param.dataType ? param.dataType : "json",
        method: param.method ? param.method : 'GET',
        success(res) {

            if (!notShowLoading) {
                Request_Utils_LoadingCount--;
                try {
                    if (Request_Utils_LoadingCount <= 0) {
                        wx.hideLoading();

                    }


                } catch (e) {
                    console.log("loading IS error");
                }
            }

            if (param.success) {
                wx.showLoading({
                    title: "数据解密中···",
                    mask: true
                })
                if (res.header && res.header.data_encrypted && res.header.data_encrypted == 'yes') {
                    let privateKeyForResponseSm2 = "ef32dbe81c033adbe33b48f95920b87755049a9c646e92477c8f256c388e5983";
                    let privateKeyForResponseRsa2 = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMErvHYQQW3UxEyeSJX0e5Vigv5/ Y0gHMvt3/p2XBCFwfNGdP1REL7jkqKVNboefZmDWTPujdCoKfe3mF4X4m8fQAKyDdFKJcsZdERE87zqIQzCeXt54xXy75KyF/Q5I7s/KLmcQYIN0fA1FMiuJGwnwaJB0kkFKSOXx/dgzzqYnAgMBAAECgYBB+V0Jea3PBB7zCBBEXtaig523q+xNml/YMPhd/Ejl3tRShwEtF4iw/i93HYYFffRqWGa8fuvau/Ccgrw//lO9h3nnbeEF1ig+/xkXDLQ7VH6s24yPOEh+bwbw9LWPKLJqPWcZAAjjmBEhp0ePlijxXXRq6ondC5SvdQWO5logiQJBAOpZHdfQXYQoCd+fLQ3S9sWgFknkKKamMxLjIMCAz+zmzjrsKV9GxkbyNrhzEpg5e8rD6guSnbVa6AZcb1ViUxMCQQDTBK40mKv69pFbMHf0psIKyIKT9nbE3qXK76KsPMegX6xghbRosUxZkzJrp/MwlJxhwoUYDFm83yJriHoygm8dAkEA5TlWH4sIbgRb5AhmoWcBSj1Uj+JEgP2AZ7ESkDlvKGJ6xtfJgBBSUYMKU1D7lzpjA+quO7Ol34aT/eTcYcBTUQJAIZ/uTm1BglUF5nz7sF1eMC+xNvigBlDgJE05I67vtGtqYVsM213dJ6zf7O2vP79+h8liQem95u27Y10085V7NQJBAM/AqbxQj3GyzRbvcJqYhWBGdDkBqqCKrtmI9S6L2fgNS0SmucjPL7ZnoHlHyRJ1jFwPBQ3/nYwGq8RrcfkpDiM=";
                    let rsaDecryptor = wx.sqtools.createRasDecryptor(privateKeyForResponseRsa2);
                    let secondDataContainerString = rsaDecryptor.decryptLong(res.data, privateKeyForResponseRsa2);
                    let secondDataContainer = JSON.parse(secondDataContainerString);
                    let firstDataContainerString = secondDataContainer.data;
                    let firstDataContainer = JSON.parse(firstDataContainerString);
                    let dataEncryptedString = firstDataContainer.data;
                    let dataJSONString = wx.sqtools.sm2.decrypt(dataEncryptedString, privateKeyForResponseSm2);
                    res.data = JSON.parse(dataJSONString);
                }

                wx.hideLoading()
                param.success(res);
            }
        },
        fail: function (res) {
            if (!notShowLoading) {
                Request_Utils_LoadingCount--;
                try {
                    if (Request_Utils_LoadingCount <= 0) {
                        wx.hideLoading();

                    }


                } catch (e) {
                    console.log("loading IS error");
                }
            }
            if (param.fail) {
                param.fail(res);
            }
        },
        complete: function () {
            // shouldShowLoading = false;


            if (param.complete) {
                param.complete();
            }
        }

    })
}

const toast = function (content) {
    wx.showToast({
        title: content ? content : "",
        icon: 'none',
        image: '',
        duration: 1500,
        mask: false,
        success: (result) => {

        },
        fail: () => {
        },
        complete: () => {
        }
    });
}
const toastSuccess = function (content) {
    wx.showToast({
        title: content ? content : "",
        icon: 'success',
        image: '',
        duration: 1500,
        mask: false,
        success: (result) => {

        },
        fail: () => {
        },
        complete: () => {
        }
    });
}
const sqlog = function (content) {
    // return false;
    console.log(content)
}
const isEmpty = function (value) {
    if (!value) {
        return true;
    }
    if (value == '') {
        return true;
    }
    return false;
}
const numberScale = function (value, digit) {
    if (digit < 0) digit = 2;
    let scaleNumber = Math.pow(10, digit);
    return Math.floor(value * scaleNumber) / scaleNumber;

}
const getInt = function (value, notAddOne) {
    let intValue = parseInt(value);


    if (notAddOne) {
        return intValue;
    } else {
        if ((intValue - value) < 0.0) {
            return intValue + 1;
        } else {
            return intValue;
        }

    }
}
const createRandom = function (digits, containNegative) {
    if (digits <= 0) digits = 1;
    let scaleValue = Math.pow(10, digits);
    if (containNegative) {

        return parseInt(Math.random() * scaleValue * 2) - scaleValue;
    } else {
        return parseInt(Math.random() * scaleValue);
    }
}
const createRandomWithRange = function (min, max) {
    let diff = max - min;
    let digit = extra(diff, 10) + 1;

    let targetValue = createRandom(digit) % diff;

    return min + targetValue;

}
const extra = function (value, root) {

    let NAN = 0;
    if (root <= 1) {
        return NAN;
    }
    if (value <= 0) {
        return NAN;
    }
    let index = 0;
    while (value >= root) {
        value = value / root;
        index++;
    }
    return index;

}
module.exports = {
    formatTime: formatTime,
    formatNumber: formatNumber,
    request: request,
    requestBackground: requestBackground,
    checkPhone: checkPhone,
    timeToSeconds: timeToSeconds,
    toast: toast,
    toastSuccess: toastSuccess,
    sqlog: sqlog,
    isEmpty: isEmpty,
    tdtt: transDateToTimestamp,
    scale: numberScale,
    getInt: getInt,
    getTwo: getTwo,
    random: createRandom,
    randomr: createRandomWithRange,
    extraRoot: extra
}
